<?php

namespace Lib;

class View {

    private $_path;
    private $_template;
    private $_layout;
    private $_var = array();

    public function __construct($path = '') {
        $path = trim($path, '/\\');
        $path = SITE_PATH . $path . DIRSEP;
        if (is_dir($path) == false) {
            throw new \Exception('Invalid view path: `' . $path . '`');
        }
        $this->_path = $path;
    }

    public function assign($key, $value) {
        $this->_var[$key] = $value;
    }
    
    public function setLayout($layout = '') {
        
        $this->_layout = !empty($layout) ? $this->_path . $layout : '';
    }
    
    public function getLayout() {
        
        return str_replace($this->_path, '', $this->_layout);
    }

    public function __get($name) {
        if (isset($this->_var[$name]))
            return $this->_var[$name];
        return '';
    }

    public function display($template, $strip = true) {
        $this->_template = $this->_path . $template;
        if (!file_exists($this->_template))
            die('Шаблона ' . $this->_template . ' не существует!');
        ob_start();
        include $this->_template;
        if(!empty($this->_layout)){
            $content = ($strip) ? $this->_strip(ob_get_clean()) : ob_get_clean();
            ob_start();
            include $this->_layout;
        }
        echo ($strip) ? $this->_strip(ob_get_clean()) : ob_get_clean();
    }

    private function _strip($data) {
        $lit = array("\\t", "\\n", "\\n\\r", "\\r\\n", "  ");
        $sp = array('', '', '', '', '');
        return str_replace($lit, $sp, $data);
    }

    public function xss($data) {
        if (is_array($data)) {
            $escaped = array();
            foreach ($data as $key => $value) {
                $escaped[$key] = $this->xss($value);
            }
            return $escaped;
        }
        return htmlspecialchars($data, ENT_QUOTES);
    }
    
    public function renderPartial($name, $params = array()){
        foreach($params as $key => $value){
            $this->assign($key, $value);
        }
        include $this->_path . $name;
    }
    
    public function renderModule($name){
        $layout = $this->getLayout();
        \Lib\Registry::get('router')->delegate($name);
        $this->setLayout($layout);
    }

    public function __($word){
        return Registry::get('trans')->get($word);
    }
}

?>
